﻿using Core.IServices;
using Library.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Core.Messages;
using Core.Dtos;
using System.Collections;
using Library.Logging;
using Core.Queries;
using Core.IRepository;
using Core.Mappers;
using Core.Aspects;

namespace Services
{
    public class ManageCacheService : BaseService, IManageCacheService
    {
        private readonly ICacheStorage cacheStorage;
        private readonly IQueryHelper<KeyValuePair<string, object>> queryHelper;

        public ManageCacheService(ICacheStorage cacheStorage, ILogger logger, IQueryHelper<KeyValuePair<string, object>> queryHelper)
        {
            this.cacheStorage = cacheStorage;
            this.queryHelper = queryHelper;
        }

        public CacheEntryDto FindByID(string id)
        {
            object value = cacheStorage.Get<object>(id);
            KeyValuePair<string, object> keyValue = new KeyValuePair<string, object>(id, value);
            return keyValue.Map<CacheEntryDto>();                        
        }

        [HandleServiceError]
        public QueryResponse<CacheEntryDto> FindBy(Request<CacheQuery> request)
        {
            var query = request.Value;
            QueryResponse<CacheEntryDto> response = new QueryResponse<CacheEntryDto>();
  
            response = queryHelper.FindBy(cacheStorage.GetAllEntries().AsQueryable(), query).Map<KeyValuePair<string, object>, CacheEntryDto>();            

            return response;
        }

        public virtual Response Delete(string id)        
        { 
            return Run(() => { cacheStorage.Remove(id); });
        }
    }
}
